﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Infrastructure.Data;
using Keepo.Models;
using Keepo.Models.Services;
using AlbumDesigner.Models.Types;
using Keepo.Helpers;
using AlbumDesigner.Models.Enums;
using AlbumDesigner.Helpers;

namespace AlbumDesigner.Controllers
{
    public class PageLayoutsController : Controller
    {
        private AlbumContext db = new AlbumContext();

        [CheckPermission(section = "PageLayouts")]
        public ActionResult Index()
        {
            return View();
        }

        [CheckPermission(section = "PageLayouts")]
        [HttpPost]
        public ActionResult GetPageLayoutsList(int categoryId, int Page = 1)
        {
            //get all the layouts of the specified Category
            var layoutsList = db.PageLayouts.Where(m => m.LayoutCategoryId == categoryId && m.IsRemoved == false).ToList();

            var layouts = layoutsList.Select(m => new PageLayoutExport(m)).ToList();

            //add the Paging settings to the layouts list
            int rowsPerPage = 12;
            int imagesCount = layouts.Count();
            int startIndex = (Page - 1) * rowsPerPage;
            int pagesCount = imagesCount / rowsPerPage;
            if (imagesCount % rowsPerPage > 0)
            {
                pagesCount++;
            }

            var layoutsPages = layouts.Skip(startIndex).Take(rowsPerPage);

            return Json(new { Layouts = layoutsPages, Pages = pagesCount });
        }

        [CheckPermission(section = "PageLayouts")]
        public ActionResult GetCategoriesList()
        {
            //get all the categories
            var categoriesList = db.LayoutCategories.ToList();

            var categories = categoriesList.Select(m => new ImageCategoryData(m)).ToList();

            return Json(categories);
        }

        [CheckPermission(section = "PageLayouts")]
        public ActionResult CategoryForm(int? id)
        {
            //edit mode
            if (id != null)
            {
                var category = db.LayoutCategories.Find(id);
                return PartialView(category);
            }
            //insert mode
            else
            {
                return PartialView();
            }
        }

        [CheckPermission(section = "PageLayouts")]
        [HttpPost]
        public ActionResult AddCategory(LayoutCategory category)
        {
            //insert this category
            db.LayoutCategories.Add(category);
            db.SaveChanges();

            return Json(new KeyValuePair<bool, string>(true, "הקטגוריה נוספה בהצלחה."));
        }

        [CheckPermission(section = "PageLayouts")]
        [HttpPost]
        public ActionResult UpdateCategory(LayoutCategory category)
        {
            //update this category
            var existingCategory = db.LayoutCategories.Find(category.LayoutCategoryId);
            existingCategory.Title = category.Title;
            existingCategory.TitleHebrew = category.TitleHebrew;

            db.SaveChanges();

            return Json(new KeyValuePair<bool, string>(true, "הקטגוריה עודכנה בהצלחה."));
        }

        [CheckPermission(section = "PageLayouts")]
        public ActionResult DeleteCategory(int id)
        {
            //find this category
            var category = new ImageCategoryData(db.LayoutCategories.Find(id));

            //get all the categories as SelectList
            ViewBag.MoveToCategoryId = new SelectList(db.LayoutCategories.Where(m => m.LayoutCategoryId != id), "LayoutCategoryId", "TitleHebrew");

            return PartialView(category);
        }

        [CheckPermission(section = "PageLayouts")]
        [HttpPost]
        public ActionResult DeleteCategory(int categoryId, int? moveToCategoryId)
        {
            //find this category
            var category = db.LayoutCategories.Find(categoryId);

            //get all layouts of category
            var categoryLayouts = db.PageLayouts.Where(m => m.LayoutCategoryId == categoryId).ToList();

            var message = "הקטגוריה " + category.TitleHebrew + " נמחקה בהצלחה.";

            if (moveToCategoryId == null)
            {
                //delete all the Layouts of this category
                if (categoryLayouts.Count > 0)
                {
                    categoryLayouts.ForEach(m => db.PageLayouts.Remove(m));
                    db.SaveChanges();
                }
            }
            else
            {
                //move all layouts of category to a different specified category
                categoryLayouts.ForEach(m => m.LayoutCategoryId = moveToCategoryId);
                db.SaveChanges();

                message = "הקטגוריה " + category.TitleHebrew + " נמחקה והסידורים שבה הועברו לקטגוריה הנבחרת.";
            }

            //delete the category
            db.LayoutCategories.Remove(category);
            db.SaveChanges();

            return Json(new KeyValuePair<bool, string>(true, message));
        }

        [CheckPermission(section = "PageLayouts")]
        [HttpPost]
        public ActionResult MoveLayoutsToCategory(string layoutsIds, int categoryId)
        {
            var layouts = layoutsIds.Split(',');

            //loop through all the specified layouts
            foreach (var layoutId in layouts)
            {
                if (!string.IsNullOrEmpty(layoutId))
                {
                    //find the PageLayout and update its Category
                    var layout = db.PageLayouts.Find(int.Parse(layoutId));
                    layout.LayoutCategoryId = categoryId;

                }
            }

            db.SaveChanges();

            return Json(new KeyValuePair<bool, string>(true, "הסידור הועבר בהצלחה."));
        }

        [CheckPermission(section = "PageLayouts")]
        [HttpPost]
        public ActionResult DeletePageLayout(string layoutsIds)
        {
            var layouts = layoutsIds.Split(',');

            //loop through all the specified layouts
            foreach (var layoutId in layouts)
            {
                if (!string.IsNullOrEmpty(layoutId))
                {
                    //find the PageLayout and delete it
                    SetPageLayoutAsRemoved(int.Parse(layoutId));
                }
            }

            return Json(new KeyValuePair<bool, string>(true, "הסידור נמחק בהצלחה."));
        }

        // Flex
        [HttpPost]
        public ActionResult RemovePageLayout(int layoutId)
        {
            SetPageLayoutAsRemoved(layoutId);
            return Json(true);
        }

        private void SetPageLayoutAsRemoved(int id)
        {
            var layout = db.PageLayouts.Find(id);

            if (layout != null)
            {
                layout.IsRemoved = true;
                db.SaveChanges();
            }
        }

        // Flex
        [HttpPost]
        public ActionResult AddPageLayout(int albumId, bool isSingle, HttpPostedFileBase xmlFile, HttpPostedFileBase thumbnailFile)
        {
            string guid = Guid.NewGuid().ToString().Substring(0, 8);
            string xmlFileName = AlbumHelper.PageLayoutXml(albumId, guid);
            string thumbnailFileName = AlbumHelper.PageLayoutThumbnailUrl(albumId, guid);

            xmlFile.SaveAs(Server.MapPath("~/") + xmlFileName);
            thumbnailFile.SaveAs(Server.MapPath("~/") + thumbnailFileName);

            PageLayoutExport pageLayout = new PageLayoutExport()
            {
                AlbumId = albumId,
                IsSingle = isSingle,
                Guid = guid,
                ThumbnailUrl = thumbnailFileName,
                XmlUrl = xmlFileName
            };

            var result = AlbumsLogic.addPageLayout(pageLayout);
            return Json(result);
        }

        // Flex
        public ActionResult GetPageLayoutCategories()
        {
            using (AlbumContext db = new AlbumContext())
            {
                var layouts = db.LayoutCategories.Select(m => new { key = m.LayoutCategoryId, english = m.Title, hebrew = m.TitleHebrew });
                return Json(layouts.ToArray(), JsonRequestBehavior.AllowGet);
            }
        }

        // Flex
        [HttpPost]
        public ActionResult GetPageLayoutsByCategoryId(int categoryId)
        {
            using (AlbumContext db = new AlbumContext())
            {
                var layouts = db.PageLayouts.Where(m => m.LayoutCategoryId == categoryId && m.IsRemoved == false).ToArray().Select(m => new PageLayoutExport(m)).ToArray();
                return Json(layouts);
            }
        }

        // Flex
        [HttpPost]
        public ActionResult GetPageLayoutsByAlbumId(int albumId)
        {
            using (AlbumContext db = new AlbumContext())
            {
                var layouts = db.PageLayouts.Where(m => m.AlbumId == albumId && m.IsRemoved == false).ToArray().Select(m => new PageLayoutExport(m)).ToArray();
                return Json(layouts);
            }
        }
    }
}
